﻿
using Microsoft.EntityFrameworkCore;
using System.Data;
using UtilsORM;
using UtilsORM.MySqlData;
////using System.Web.Script.Serialization;

namespace ServiceWeb.DBGateway
{
    public class DBIotDevice
    {


        EFYihongIotContext ef = new EFYihongIotContext();
        public iot_device getDevice(string dguid)
        {
            return ef.iot_device.Where(c => c.d_guid == dguid).FirstOrDefault();
        }

        public List<iot_device> getClientDeviceList(string cguid)
        {
            List<iot_device> list = ef.iot_device.Where(c => c.d_c_guid == cguid && c.d_status == 0).ToList();
            list.AddRange(ef.iot_device.Where(c => c.d_c_guid == "00000000-0000-0000-0000-000000000000").ToList());
            return list;
        }
        public List<iot_device> getClientDeviceList()
        {
            List<iot_device> list = ef.iot_device.Where(c => c.d_status == 0).ToList();
            list.AddRange(ef.iot_device.Where(c => c.d_c_guid == "00000000-0000-0000-0000-000000000000").ToList());
            return list;
        }
        /// <summary>
        /// m_attribute 1,2
        /// </summary>
        /// <param name="cguid"></param>
        /// <returns></returns>
        public List<iot_device> getClientCommandDeviceByList(string cguid)
        {
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0 && (m.m_attribute == 1 || m.m_attribute == 2 || m.m_attribute == 4) && d.d_c_guid == cguid
                    select d).ToList();

        }

        public List<iot_device> getDeviceByNoProductList()
        {
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0 && (m.m_attribute == 1 || m.m_attribute == 2) && d.d_is_template == 0
                    select d).ToList();

        }
        public List<iot_device> getDeviceByProductList(string p_guid)
        {
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0  && d.d_p_guid == p_guid
                    select d).ToList();

        }
        public iot_device getDeviceByProductModelNo(string p_guid, int modelno)
        {
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && d.d_p_model_no == modelno && d.d_p_guid == p_guid
                    select d).FirstOrDefault();

        }

        public List<iot_device> getDeviceGateWayList(string cguid)
        {
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0 && m.m_attribute == 3 && d.d_c_guid == cguid
                    select d).ToList();
        }
        public List<iot_device> getDeviceGateWayList()
        {
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0 && m.m_attribute == 3
                    select d).ToList();
        }
        private static object obj = new object();
        public bool saveAll(MagerLoginInfo LoginUserInfo, iot_device reqDevice)
        {
            lock (obj)
            {
                iot_device_model device_Model = new DBIotDeviceModel().getModel(reqDevice.d_model_guid);
                iot_device_model_type model_Type = new DBIotDeviceModelType().getModelType(device_Model.m_type_guid);


                //先查一下有没重复提交
                iot_device model = ef.iot_device.Where(c => c.d_guid == reqDevice.d_guid).FirstOrDefault();
                if (model == null)
                {
                    //查编码
                    iot_device getcode = ef.iot_device.OrderByDescending(c => Convert.ToInt32(c.d_code)).FirstOrDefault();
                    if (getcode != null)
                    {
                        reqDevice.d_code = (int.Parse(getcode.d_code) + 1).ToString();
                    }
                    else
                    {
                        reqDevice.d_code = "20001";
                    }
                    //写入
                    reqDevice.d_visible = 0;
                    reqDevice.d_mod_time = DateTime.Now;
                    reqDevice.d_add_time = DateTime.Now;
                    //reqDevice.d_c_guid = LoginUserInfo.userCompanyGuid;
                    reqDevice.d_p_model_no = 0;
                    if (!string.IsNullOrWhiteSpace(reqDevice.d_p_guid))
                    {
                        reqDevice.d_is_template = 1;
                        iot_device deviceproduct = ef.iot_device.Where(c => c.d_p_guid == reqDevice.d_p_guid && c.d_p_model_no!=null).OrderByDescending(c => c.d_p_model_no).FirstOrDefault();
                        if (deviceproduct != null && deviceproduct.d_p_model_no != null)
                        {
                            reqDevice.d_p_model_no = deviceproduct.d_p_model_no + 1;
                        }
                        reqDevice.d_c_guid = ef.iot_product.Where(c => c.p_guid == reqDevice.d_p_guid).FirstOrDefault().p_c_guid;
                    }
                    else
                    {
                        reqDevice.d_is_template = 0;
                    }
                    ef.iot_device.Add(reqDevice);
                    ef.SaveChanges();
                }
                else
                {
                    model.d_name = reqDevice.d_name;
                    model.d_model_guid = reqDevice.d_model_guid;
                    model.d_remark = reqDevice.d_remark;
                    model.d_parameter = reqDevice.d_parameter;
                    model.d_parameter_init = reqDevice.d_parameter_init;
                    model.d_mod_time = DateTime.Now;
                    model.d_status = reqDevice.d_status;
                    model.d_group_guid = reqDevice.d_group_guid;
                    model.d_gw_d_guid = reqDevice.d_gw_d_guid;
                    model.d_channel = reqDevice.d_channel;
                    model.d_register_address = reqDevice.d_register_address;
                    ef.iot_device.Update(model);
                    ef.SaveChanges();
                }
            }
            return true;

        }

        public bool saveGateWay(MagerLoginInfo LoginUserInfo, iot_device reqDevice, iot_device_gateway reqGateway)
        {
            lock (obj)
            {
                iot_device_model device_Model = new DBIotDeviceModel().getModel(reqDevice.d_model_guid);
                iot_device_model_type model_Type = new DBIotDeviceModelType().getModelType(device_Model.m_type_guid);


                //先查一下有没重复提交
                iot_device model = ef.iot_device.Where(c => c.d_guid == reqDevice.d_guid).FirstOrDefault();
                if (model == null)
                {
                    //查编码
                    iot_device getcode = ef.iot_device.OrderByDescending(c => c.d_id).FirstOrDefault();
                    if (getcode != null)
                    {
                        reqDevice.d_code = (int.Parse(getcode.d_code) + 1).ToString();
                    }
                    else
                    {
                        reqDevice.d_code = "20001";
                    }
                    //写入
                    reqDevice.d_visible = 0;
                    reqDevice.d_add_time = DateTime.Now;
                    reqDevice.d_p_model_no = 0;
                    if (!string.IsNullOrWhiteSpace(reqDevice.d_p_guid))
                    {
                        reqDevice.d_is_template = 1;
                        iot_device deviceproduct = ef.iot_device.Where(c => c.d_p_guid == reqDevice.d_p_guid).OrderByDescending(c => c.d_id).FirstOrDefault();
                        if (deviceproduct != null && deviceproduct.d_p_model_no != null)
                        {
                            reqDevice.d_p_model_no = deviceproduct.d_p_model_no + 1;
                        }

                        reqDevice.d_c_guid = ef.iot_product.Where(c => c.p_guid == reqDevice.d_p_guid).FirstOrDefault().p_c_guid;
                    }
                    else
                    {
                        reqDevice.d_is_template = 0;
                    }

                    reqDevice.d_gw_d_guid = reqDevice.d_guid;
                    ef.iot_device.Add(reqDevice);
                    ef.SaveChanges();

                    //香橙派网关
                    //查最新的code
                    string gwcode = reqDevice.d_code;

                    //判断是否网关，如果是 写入iot_device_gateway
                    iot_device_gateway gateway = new iot_device_gateway();
                    gateway.gw_code = gwcode;
                    gateway.gw_guid = Guid.NewGuid().ToString();
                    gateway.gw_deviceid = "";
                    gateway.gw_system = reqGateway.gw_system;
                    gateway.gw_d_guid = reqDevice.d_guid;
                    gateway.gw_add_time = DateTime.Now;
                    ef.iot_device_gateway.Add(gateway);
                    ef.SaveChanges();

                }
                else
                {
                    model.d_name = reqDevice.d_name;
                    model.d_model_guid = reqDevice.d_model_guid;
                    model.d_remark = reqDevice.d_remark;
                    model.d_parameter = reqDevice.d_parameter;
                    model.d_parameter_init = reqDevice.d_parameter_init;
                    model.d_mod_time = DateTime.Now;
                    model.d_status = reqDevice.d_status;
                    model.d_group_guid = reqDevice.d_group_guid;
                    model.d_gw_d_guid = reqDevice.d_gw_d_guid;
                    model.d_channel = reqDevice.d_channel;
                    ef.iot_device.Update(model);
                    ef.SaveChanges();


                    iot_device_gateway gateway = ef.iot_device_gateway.Where(c => c.gw_d_guid == reqDevice.d_guid).FirstOrDefault();
                    gateway.gw_system = reqGateway.gw_system;
                    ef.iot_device_gateway.Update(gateway);
                    ef.SaveChanges();

                }
            }
            return true;

        }
        public List<Dictionary<string, string>> getDeviceExtInfo(string dguid)
        {
            List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();

            string sql = "select  a.* ,m.m_code,m.m_name machine_model, (select d_name from iot_device where d_guid=a.d_gw_d_guid) gwname from iot_device a inner join iot_device_model m on m.m_guid=d_model_guid  where d_guid='" + dguid + "'";
            DataTable dt = MySqlYihongFileServer.GetDataTable(sql);

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, string> directory = new Dictionary<string, string>();
                directory.Add("d_guid", dr["d_guid"].ToString());
                directory.Add("d_code", dr["d_code"].ToString());
                directory.Add("d_name", dr["d_name"].ToString());
                directory.Add("d_channel", dr["d_channel"].ToString());
                directory.Add("gwname", dr["gwname"].ToString());
                directory.Add("d_parameter", dr["d_parameter"].ToString());
                directory.Add("d_parameter_init", dr["d_parameter_init"].ToString());

                iot_device_live_state gwState = new DBIotDeviceLiveStateCache().getGateWayIsOnlineByCache(dr["d_gw_d_guid"].ToString());
                if (gwState != null)
                {
                    directory.Add("gwstate", "在线");
                }
                else if (gwState == null)
                {
                    directory.Add("gwstate", "离线");
                }
                list.Add(directory);
            }
            return list;
        }

        public bool del(string dguid)
        {
            ef.iot_device.Where(c => c.d_guid == dguid).ExecuteDelete();           
            return true;
        }


        public bool changeStatus(string dguid)
        {
            iot_device device = ef.iot_device.Where(c => c.d_guid == dguid).FirstOrDefault();
            if (device != null)
            {
                if (device.d_status == 0)
                {
                    device.d_status = 1;
                }
                else
                {
                    device.d_status = 0;
                }
                ef.SaveChanges();
            }
            return true;
        }
        public List<iot_device> getDeviceGateWayByProductList(string p_guid)
        {
            EFYihongIotContext ef = new EFYihongIotContext();
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0 && m.m_attribute == 3 && d.d_p_guid == p_guid
                    select d).ToList();
        }
        public List<iot_device> getDeviceGateWayAllList()
        {
            EFYihongIotContext ef = new EFYihongIotContext();
            return (from d in ef.iot_device
                    join m in ef.iot_device_model on d.d_model_guid equals m.m_guid
                    where d.d_status == 0 && m.m_status == 0 && m.m_attribute == 3
                    select d).ToList();
        }
    }
}
